package com.zc.emos.wx.config.shiro;

import com.zc.emos.wx.db.pojo.TbUser;
import com.zc.emos.wx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName OAuth2Realm.java
 * @Description 定义认证与授权的方法
 * @createTime 2021年11月30日 14:30:00
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;



    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //执行流程---  先认证---> 再授权，  在认证的过程中，传入三个参数
        //SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,accessToken,getName());
        //用户信息，token，realm的名字
        //所以在授权的时候就可以直接getPrimaryPrincipal，获得对象
        TbUser user = (TbUser)principalCollection.getPrimaryPrincipal();
        //根据对象获取id
        Integer userId = user.getId();
        //根据userid获取权限
        Set<String> permsSet = userService.searchUserPermissions(userId);
        //将权限返回给info
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // 从令牌中获取userId，然后检测该账户是否被冻结。
        String accessToken = (String) authenticationToken.getPrincipal();
        //通过令牌获取id
        int userId = jwtUtil.getUserId(accessToken);
        TbUser user = userService.searchById(userId);
        if(user==null){
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        // 往info对象中添加用户信息、Token字符串
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                user, accessToken, getName()
        );

        return info;
    }
}
